var dfly = {};

load('Module.js');
load('../js/ModuleModel.js');

function dflyServer(request) {
  
   var content = "";
     
   try {
      
      // Build the GETparams associative array
      var queryString = request.getQueryString();
      var GETparams = {};
      if(queryString) {
         var pairValues = queryString.split('&');
         for(var i = 0 ; i < pairValues.length; i++) {
            var a = pairValues[i].split('=');
            GETparams[a[0]] = a[1];
         }
      }
      
      
      var  m = dfly.ModuleModel.get(request.requestURI);
      if(m) {
         var runMo = new dfly.Module(m);
         runMo.setOutput = function(key,val) {
            if(typeof val == "string" || typeof val == "number") { 
               content += val;
            }
            else if(typeof val == "object" && val.size) {
               content += "array";
            }
         };
         runMo.run(GETparams);
      }
      else {
         content += "Module not found: "+request.requestURI;
      }
   }
   catch(ex) {
      content += "Exception: "+ex.message;
   }
     
   return {
      headers: {contentType: 'text/html'},
      body: '<html><body>'+content+'</body></html>'
   };  
   
}
